package admin

import (
	"gitee.com/gopher2011/gin"
	"gitee.com/gopher2011/mall/app/dao"
	"gitee.com/gopher2011/mall/app/service"
	"net/http"
	"strconv"
)

// 首页人气推荐管理 /home/recommendProduct
var SmsHomeRecommendProduct = &smsHomeRecommendProductApi{}

type smsHomeRecommendProductApi struct{}

// 添加首页推荐 /create Post dao.SmsHomeRecommendProduct
func (it *smsHomeRecommendProductApi) Create(r *gin.Context) {
	// 将请求参数解析到 ptr上
	var ptr dao.SmsHomeRecommendProductReq
	err := r.Parse(&ptr)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
		r.Abort()
	}
	res, err := service.SmsHomeRecommendProduct.Create(ptr)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{"msg": "添加首页推荐失败!"})
	} else {
		r.JSON(http.StatusOK, gin.H{"msg": "添加首页推荐成功!", "data": res})
	}
}

// 修改推荐排名 /update/sort/:id Post 参数: id,sort
func (it *smsHomeRecommendProductApi) UpdateSort(r *gin.Context) {
	id, _ := strconv.Atoi(r.Param("id"))
	sort, _ := strconv.Atoi(r.PostForm("sort"))
	res, err := service.SmsHomeRecommendProduct.UpdateSort(id, sort)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{"msg": "修改推荐排名失败!"})
	} else {
		r.JSON(http.StatusOK, gin.H{"msg": "修改推荐排名成功!", "data": res})
	}
}

//批量删除推荐 /delete Post 参数:ids[]int
func (it *smsHomeRecommendProductApi) Delete(r *gin.Context) {
	ids := make([]int, 0)
	for _, v := range r.PostFormArray("ids") {
		id, _ := strconv.Atoi(v)
		ids = append(ids, id)
	}
	res, err := service.SmsHomeRecommendProduct.Delete(ids)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{"msg": "批量删除推荐失败!"})
	} else {
		r.JSON(http.StatusOK, gin.H{"msg": "批量删除推荐成功!", "data": res})
	}
}

// 批量修改推荐状态 /update/recommend_status Post 参数:ids[]int,recommend_status
func (it *smsHomeRecommendProductApi) UpdateRecommendStatus(r *gin.Context) {
	ids := make([]int, 0)
	for _, v := range r.PostFormArray("ids") {
		id, _ := strconv.Atoi(v)
		ids = append(ids, id)
	}
	status, _ := strconv.Atoi(r.PostForm("recommend_status"))
	res, err := service.SmsHomeRecommendProduct.UpdateRecommendStatus(ids, status)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{"msg": "批量修改推荐状态失败!"})
	} else {
		r.JSON(http.StatusOK, gin.H{"msg": "批量修改推荐状态成功!", "data": res})
	}
}

// 分页查询推荐 /list Get
func (it *smsHomeRecommendProductApi) List(r *gin.Context) {
	// 将请求参数解析到 ptr上
	var ptr dao.SmsHomeRecommendProductList
	err := r.Parse(&ptr)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
		r.Abort()
	}
	res, err := service.SmsHomeRecommendProduct.List(ptr)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{"msg": "分页查询推荐失败!"})
	} else {
		r.JSON(http.StatusOK, gin.H{"msg": "分页查询推荐成功!", "data": res})
	}
}
